package com.itheima.web.servlet;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.Category;
import com.itheima.domain.Route;
import com.itheima.service.CategoryService;
import com.itheima.service.RouteService;
import com.itheima.utils.BeanFactoryUtils;
import com.itheima.web.base.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@WebServlet(name = "RouteServlet" , urlPatterns = "/route")
@MultipartConfig
public class RouteServlet extends BaseServlet {


    /**
     * 跳转页面之前 先查询原数据
     * @param request
     * @param response
     */
    private void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获得请求数据
        String rid = request.getParameter("rid");

        //2.根据rid查询线路对象数据
        RouteService routeService = (RouteService) BeanFactoryUtils.getBean("routeService");
        Route route = routeService.findById(Integer.valueOf(rid));


        //查询导航条数据
        CategoryService categoryService = (CategoryService) BeanFactoryUtils.getBean("categoryService");
        List<Category> categoryList = categoryService.findAll();



        //3.请求转发给route_edit.jsp页面
        request.setAttribute("route" , route);
        request.setAttribute("categoryList" , categoryList);
        request.getRequestDispatcher("/route_edit.jsp").forward(request,response);

    }

    /**
     * 查询所有
     * @param request
     * @param response
     */
    private void findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获得参数
        String pageNumberStr = request.getParameter("pageNumber");
        String cid = request.getParameter("cid");
        int pageSize = 5; //暂时写死

        int pageNumber =1 ;
        try {
            pageNumber = Integer.valueOf(pageNumberStr);
            if(pageNumber<1){
                pageNumber=1;
            }
        } catch (NumberFormatException e) {
        }

        //2.调用service
        RouteService routeService = (RouteService) BeanFactoryUtils.getBean("routeService");


        PageInfo<Route> pageInfo = routeService.findAll(pageNumber,pageSize,Integer.valueOf(cid));

        System.out.println(pageInfo);
        //3.将数据转为json返回给浏览器端
        String json = new ObjectMapper().writeValueAsString(pageInfo);
        System.out.println(json);
        response.getWriter().print(json);
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获得请求参数
        String rid = request.getParameter("rid");
        RouteService routeService = (RouteService) BeanFactoryUtils.getBean("routeService");
        //调用service执行删除
        routeService.delete(Integer.valueOf(rid));
        //重新跳转查询所有页面
        response.sendRedirect(request.getContextPath() + "/route?action=findAll");
    }

    private void update(HttpServletRequest request, HttpServletResponse response) {
        try {
            //1.获得数据
            //1.1 获得map
            Map<String, String[]> map = request.getParameterMap();
            //1.2 创建Route
            Route route = new Route();
            //1.3 使用BeanUtils进行封装数据
            BeanUtils.copyProperties(route , map);

            System.err.println(route);

            //2.处理数据 (保存)
            RouteService routeService = (RouteService) BeanFactoryUtils.getBean("routeService");
            routeService.update(route);
            //3.响应结果
            response.sendRedirect(request.getContextPath() + "/route?action=findAll");



        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addRoute(HttpServletRequest request, HttpServletResponse response) {
        try {
            //1.获得数据
            //1.1 获得map
            Map<String, String[]> map = request.getParameterMap();
            //1.2 创建Route
            Route route = new Route();
            //1.3 使用BeanUtils进行封装数据
            BeanUtils.copyProperties(route , map);

            //1.4 特殊处理图片
            Part part = request.getPart("image");
            if(part!=null && part.getSize()>0){
                // 获得图片名
                String fileName = part.getSubmittedFileName();
                // 生成一个随机的名称
                fileName = IdUtil.simpleUUID() + fileName;

                //操作文件
                InputStream is = part.getInputStream();

                //获得项目在本地的真实路径
                String realPath = getServletContext().getRealPath("/img/product/small");

                //创建输出流
                FileOutputStream os = new FileOutputStream(realPath + "/" + fileName );

                //流转换
                IoUtil.copy(is , os);
                is.close();
                os.close();
                System.out.println(realPath + "/" + fileName);
                route.setRimage("img/product/small/"+fileName);
            }


            //2.处理数据 (保存)
            RouteService routeService = (RouteService) BeanFactoryUtils.getBean("routeService");
            routeService.save(route);
            //3.响应结果
            response.sendRedirect(request.getContextPath() + "/route?action=findAll");



        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
